# -*- coding: utf-8 -*-
"""
报表分享服务 - 生成报表分享页面
"""
import os
from typing import Dict, Optional
from pathlib import Path
from jinja2 import Template
from datetime import datetime

from app.services.report_service import ReportRunService, ReportTemplateService


class ReportShareService:
    """报表分享服务"""
    
    @staticmethod
    def generate_share_page(run_id: int, base_url: str = None) -> str:
        """
        生成报表分享页面HTML
        :param run_id: 运行ID
        :param base_url: 基础URL（用于构建预览和下载链接）
        :return: HTML内容
        """
        # 获取运行记录
        run = ReportRunService.get_run_by_id(run_id)
        if not run:
            return ReportShareService._generate_error_page(f"运行记录 ID: {run_id} 不存在")
        
        # 获取模板信息
        template = None
        if run.get('template_code'):
            template = ReportTemplateService.get_template_by_code(run['template_code'])
        
        template_name = template.get('template_name') if template else run.get('template_code', '未知模板')
        
        # 获取文件列表
        files = ReportRunService.get_run_files(run_id)
        
        # 准备模板变量
        report_title = run.get('title') or template_name
        status = run.get('status', 'unknown')
        
        # 格式化时间范围
        time_start = run.get('time_start')
        time_end = run.get('time_end')
        if time_start and time_end and time_start != 'None' and time_end != 'None' and time_start != 'null' and time_end != 'null':
            time_range = f"{time_start} ~ {time_end}"
        else:
            time_range = "全部数据"
        
        created_at = run.get('created_at', '-')
        finished_at = run.get('finished_at')
        duration = ReportShareService._calculate_duration(created_at, finished_at) if finished_at else '-'
        error_message = run.get('error_message')
        
        # 格式化文件列表
        formatted_files = []
        for file in files:
            # 格式化创建时间
            file_created_at = file.get('created_at', '-')
            if file_created_at and hasattr(file_created_at, 'strftime'):
                file_created_at = file_created_at.strftime('%Y-%m-%d %H:%M:%S')
            elif file_created_at and isinstance(file_created_at, str):
                # 已经是字符串，直接使用
                pass
            else:
                file_created_at = '-'
            
            formatted_files.append({
                'id': file['id'],
                'file_type': file.get('file_type', 'unknown'),
                'file_size': ReportShareService._format_file_size(file.get('file_size')),
                'created_at': file_created_at
            })
        
        # 获取HTML模板
        html_template = ReportShareService._get_share_template()
        
        # 渲染HTML
        template = Template(html_template)
        html = template.render(
            report_title=report_title,
            template_name=template_name,
            status=status,
            time_range=time_range,
            created_at=created_at,
            finished_at=finished_at,
            duration=duration,
            error_message=error_message,
            files=formatted_files,
            run_id=run_id,
            base_url=base_url or ''
        )
        
        return html
    
    @staticmethod
    def _get_share_template() -> str:
        """获取分享页面HTML模板"""
        return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ report_title }} - 报表详情</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        .header .subtitle {
            font-size: 14px;
            opacity: 0.9;
        }
        .content {
            padding: 30px;
        }
        .info-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }
        .info-section h2 {
            font-size: 20px;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }
        .info-item {
            display: flex;
            flex-direction: column;
        }
        .info-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .info-value {
            font-size: 16px;
            color: #333;
            font-weight: 500;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-success {
            background: #d4edda;
            color: #155724;
        }
        .status-running {
            background: #fff3cd;
            color: #856404;
        }
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
        .files-section {
            margin-top: 30px;
        }
        .files-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .files-table thead {
            background: #667eea;
            color: white;
        }
        .files-table th {
            padding: 15px;
            text-align: left;
            font-weight: 500;
            font-size: 14px;
        }
        .files-table td {
            padding: 15px;
            border-bottom: 1px solid #e9ecef;
        }
        .files-table tbody tr:hover {
            background: #f8f9fa;
        }
        .file-type-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
            text-transform: uppercase;
        }
        .file-type-html {
            background: #e3f2fd;
            color: #1976d2;
        }
        .file-type-excel {
            background: #e8f5e9;
            color: #388e3c;
        }
        .btn {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 4px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            margin-right: 8px;
        }
        .btn-primary {
            background: #667eea;
            color: white;
        }
        .btn-primary:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
        }
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(108, 117, 125, 0.3);
        }
        .error-alert {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #dc3545;
        }
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{{ report_title }}</h1>
            <div class="subtitle">报表详情页面</div>
        </div>
        <div class="content">
            <div class="info-section">
                <h2>基本信息</h2>
                <div class="info-grid">
                    <div class="info-item">
                        <div class="info-label">模板名称</div>
                        <div class="info-value">{{ template_name }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">运行状态</div>
                        <div class="info-value">
                            {% if status == 'success' %}
                                <span class="status-badge status-success">成功</span>
                            {% elif status == 'running' %}
                                <span class="status-badge status-running">运行中</span>
                            {% elif status == 'failed' %}
                                <span class="status-badge status-failed">失败</span>
                            {% else %}
                                <span class="status-badge">{{ status }}</span>
                            {% endif %}
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">统计时间</div>
                        <div class="info-value">{{ time_range }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">创建时间</div>
                        <div class="info-value">{{ created_at }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">完成时间</div>
                        <div class="info-value">{{ finished_at or '-' }}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">执行耗时</div>
                        <div class="info-value">{{ duration }}</div>
                    </div>
                </div>
            </div>

            {% if error_message %}
            <div class="error-alert">
                <strong>错误信息：</strong>{{ error_message }}
            </div>
            {% endif %}

            <div class="files-section">
                <h2 style="margin-bottom: 20px; color: #333; font-size: 20px; padding-bottom: 10px; border-bottom: 2px solid #667eea;">生成的文件</h2>
                {% if files %}
                <table class="files-table">
                    <thead>
                        <tr>
                            <th>文件类型</th>
                            <th>文件大小</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for file in files %}
                        <tr>
                            <td>
                                <span class="file-type-badge file-type-{{ file.file_type }}">{{ file.file_type.upper() }}</span>
                            </td>
                            <td>{{ file.file_size }}</td>
                            <td>{{ file.created_at }}</td>
                            <td>
                                {% if file.file_type == 'html' %}
                                    <a href="{{ base_url }}/api/reports/runs/{{ run_id }}/files/{{ file.id }}/preview" 
                                       target="_blank" 
                                       class="btn btn-primary">预览</a>
                                {% endif %}
                                <a href="{{ base_url }}/api/reports/runs/{{ run_id }}/files/{{ file.id }}/download" 
                                   class="btn btn-secondary">下载</a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
                {% else %}
                <div class="empty-state">
                    <div class="empty-state-icon">📄</div>
                    <div>暂无文件</div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</body>
</html>
        """
    
    @staticmethod
    def _format_file_size(size_bytes) -> str:
        """格式化文件大小"""
        if not size_bytes:
            return '0 B'
        size = float(size_bytes)
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size < 1024.0:
                return f"{size:.2f} {unit}"
            size /= 1024.0
        return f"{size:.2f} TB"
    
    @staticmethod
    def _calculate_duration(start_time: str, end_time: str) -> str:
        """计算执行耗时"""
        if not start_time or not end_time:
            return '-'
        try:
            start = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
            end = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
            duration = (end - start).total_seconds()
            days = int(duration // 86400)
            hours = int((duration % 86400) // 3600)
            minutes = int((duration % 3600) // 60)
            seconds = int(duration % 60)
            if days > 0:
                return f"{days}天{hours}时"
            elif hours > 0:
                return f"{hours}时{minutes}分"
            elif minutes > 0:
                return f"{minutes}分{seconds}秒"
            else:
                return f"{seconds}秒"
        except:
            return '-'
    
    @staticmethod
    def _generate_error_page(message: str) -> str:
        """生成错误页面"""
        return f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>报表不存在</title>
    <style>
        body {{ 
            font-family: Arial, sans-serif; 
            text-align: center; 
            padding: 50px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }}
        .error-container {{
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }}
        .error {{ color: #dc3545; }}
    </style>
</head>
<body>
    <div class="error-container">
        <h1 class="error">报表不存在</h1>
        <p>{message}</p>
    </div>
</body>
</html>
        """

